<template>
  <div class="app-container">
    <div class="data-clean">
      <!-- 左侧内容区域 -->
      <div class="main-content">
        <div class="left-panel">
          <div class="file-info">
            <div class="info-item">
              <span class="label">文档名称：</span>
              <span class="value">{{ fileInfo.name || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">文档路径：</span>
              <span class="value">{{ fileInfo.path || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">文件大小：</span>
              <span class="value">{{ formatFileSize(fileInfo.size) || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ fileInfo.createTime || '-' }}</span>
            </div>
          </div>

          <el-tabs v-model="activeTab" class="function-tabs">
            <el-tab-pane label="导入文档" name="import">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadFileUrl"
                :headers="headers"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 .txt, .doc, .docx, .pdf, .xlsx, .xls, .png, .jpg, .jpeg, .gif 格式文件
                  </div>
                </template>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="导出结果" name="export">
              <el-button type="primary" @click="handleExport">导出清洗结果</el-button>
            </el-tab-pane>
          </el-tabs>

          <div class="preview-area">
            <div class="preview-header">
              <span>文档内容预览</span>
            </div>
            <div class="preview-content">
              <!-- PDF预览 -->
              <pdf-viewer v-if="fileType === 'pdf'" :url="fileUrl" />
              <!-- Word文档预览 -->
              <div v-else-if="['doc', 'docx'].includes(fileType)" class="doc-preview" v-html="docContent"></div>
              <!-- Excel预览 -->
              <div v-else-if="fileType === 'excel'" class="excel-preview" v-html="docContent"></div>
              <!-- 图片预览 -->
              <div v-else-if="fileType === 'image'" class="image-preview">
                <img :src="fileUrl" alt="图片预览" />
              </div>
              <!-- 文本文件预览 -->
              <pre v-else-if="fileType === 'txt'" class="text-preview">{{ fileContent }}</pre>
              <!-- 不支持的文件类型 -->
              <div v-else class="unsupported-file">
                不支持预览该类型的文件
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧配置面板 -->
        <div class="right-panel">
          <div class="config-panel">
            <div class="config-title">清洗配置</div>
            
            <!-- 基础清洗选项 -->
            <div class="config-section">
              <div class="section-title">基础清洗选项</div>
              <div class="config-items">
                <el-switch
                  v-for="(item, key) in basicConfig"
                  :key="key"
                  v-model="item.value"
                  :active-value="1"
                  :inactive-value="0"
                  :active-text="item.label"
                  @change="(val) => handleConfigToggle(item, key, val)"
                />
              </div>
            </div>

            <!-- 高级清洗选项 -->
            <div class="config-section">
              <div class="section-title">高级清洗选项</div>
              <div class="config-items">
                <el-switch
                  v-for="(item, key) in advancedConfig"
                  :key="key"
                  v-model="item.value"
                  :active-value="1"
                  :inactive-value="0"
                  :active-text="item.label"
                  @change="(val) => handleConfigToggle(item, key, val)"
                />
              </div>
            </div>

            <!-- 自定义规则 -->
            <div class="config-section">
              <div class="section-title">自定义规则</div>
              <div class="custom-rule">
                <el-input
                  v-model="customPattern"
                  placeholder="输入正则表达式"
                  class="custom-input"
                >
                  <template #append>
                    <el-button @click="handleAddRule">添加</el-button>
                  </template>
                </el-input>
              </div>
              <div class="rule-list">
                <el-tag
                  v-for="(rule, index) in customRules"
                  :key="index"
                  closable
                  @close="handleRemoveRule(index)"
                >
                  {{ rule }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="bottom-actions">
        <el-button type="primary" @click="handleClean">开始清洗</el-button>
        <el-button @click="handleSaveConfig">保存配置</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.data-clean {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.main-content {
  display: flex;
  gap: 20px;
}

.left-panel {
  flex: 1;
  min-width: 0;
}

.right-panel {
  width: 400px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.config-panel {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  flex-grow: 1;
}

.config-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.config-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
}

.config-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.custom-rule {
  margin-bottom: 15px;
}

.custom-input {
  width: 100%;
}

.rule-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.el-switch) {
  width: 100%;
  justify-content: space-between;
}

:deep(.el-switch__label) {
  position: absolute;
  left: 0;
}

:deep(.el-switch__core) {
  margin-left: auto;
}

.file-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  margin-bottom: 10px;
  line-height: 24px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #606266;
  margin-right: 10px;
}

.value {
  color: #333;
}

.function-tabs {
  margin-bottom: 20px;
}

.preview-area {
  flex-grow: 1;
  margin: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.preview-header {
  padding: 12px 15px;
  border-bottom: 1px solid #dcdfe6;
  background: #f5f7fa;
  font-weight: bold;
}

.preview-content {
  min-height: 300px;
  padding: 15px;
}

.text-preview {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
  margin: 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  max-height: 500px;
  overflow: auto;
}

.doc-preview {
  padding: 10px;
  max-height: 500px;
  overflow: auto;
}

.excel-preview {
  padding: 10px;
  max-height: 500px;
  overflow: auto;
}

.excel-preview :deep(table) {
  width: 100%;
  border-collapse: collapse;
}

.excel-preview :deep(td),
.excel-preview :deep(th) {
  border: 1px solid #dcdfe6;
  padding: 8px;
  text-align: left;
}

.excel-preview :deep(th) {
  background-color: #f5f7fa;
}

.image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  max-height: 500px;
  overflow: auto;
}

.image-preview img {
  max-width: 100%;
  max-height: 480px;
  object-fit: contain;
}

.unsupported-file {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.bottom-actions {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}
</style>

<script setup name="DataClean">
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';
import { UploadFilled } from '@element-plus/icons-vue';
import mammoth from 'mammoth';
import * as XLSX from 'xlsx';
import PdfViewer from '@/components/PdfViewer/index.vue';
import request from '@/utils/request';

const activeTab = ref('import');
const fileInfo = ref({
  name: '',
  path: '',
  size: 0,
  createTime: ''
});
const fileUrl = ref('');
const fileContent = ref('');
const docContent = ref('');

// Assuming you have a cleaningConfigId from the backend after uploading a file
const cleaningConfigId = ref(null);

// 上传文件服务器地址
const uploadFileUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload';
// 上传文件请求头
const headers = { Authorization: 'Bearer ' + getToken() };

// 文件类型
const fileType = computed(() => {
  if (!fileUrl.value) return '';
  const ext = fileUrl.value.split('.').pop().toLowerCase();
  switch (ext) {
    case 'pdf': return 'pdf';
    case 'doc':
    case 'docx': return 'doc';
    case 'txt': return 'txt';
    case 'xlsx':
    case 'xls': return 'excel';
    case 'png':
    case 'jpg':
    case 'jpeg':
    case 'gif': return 'image';
    default: return '';
  }
});

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB'];
  let index = 0;
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024;
    index++;
  }
  return `${size.toFixed(2)} ${units[index]}`;
};

// 上传前校验
const handleBeforeUpload = (file) => {
  const isValidType = ['txt', 'doc', 'docx', 'pdf', 'xlsx', 'xls', 'png', 'jpg', 'jpeg', 'gif'].includes(
    file.name.split('.').pop().toLowerCase()
  );
  if (!isValidType) {
    ElMessage.error('只能上传txt/doc/docx/pdf/xlsx/xls/png/jpg/jpeg/gif格式文件！');
    return false;
  }
  return true;
};

// 上传成功回调
const handleUploadSuccess = async (response) => {
  console.log('Upload response:', response);
  if (response.code === 200) {
    // 更新文件信息
    fileInfo.value = {
      name: response.originalFilename || response.fileName,
      path: response.url || response.fileName,
      size: response.size || 0,
      createTime: new Date().toLocaleString()
    };

    // 获取文件大小
    try {
      const fileResponse = await fetch(fileUrl.value, { method: 'HEAD' });
      const contentLength = fileResponse.headers.get('content-length');
      if (contentLength) {
        fileInfo.value.size = parseInt(contentLength);
      }
    } catch (error) {
      console.error('获取文件大小失败:', error);
    }

    if (response.url) {
      fileUrl.value = response.url;
    } else if (response.fileName) {
      fileUrl.value = import.meta.env.VITE_APP_BASE_API + response.fileName;
    }

    console.log('Final URL:', fileUrl.value);

    try {
      if (fileType.value === 'txt') {
        const response = await fetch(fileUrl.value);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        fileContent.value = await response.text();
      } else if (['doc', 'docx'].includes(fileType.value)) {
        const response = await fetch(fileUrl.value);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const arrayBuffer = await response.arrayBuffer();
        const result = await mammoth.convertToHtml({ arrayBuffer });
        docContent.value = result.value;
      } else if (fileType.value === 'excel') {
        const response = await fetch(fileUrl.value);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const arrayBuffer = await response.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const htmlTable = XLSX.utils.sheet_to_html(firstSheet);
        docContent.value = htmlTable;
      }
      ElMessage.success('文件上传成功');

      // Simulate getting a cleaningConfigId (you should get this from the backend)
      // For now, we'll assume it's returned in the upload response or set manually
      cleaningConfigId.value = 1; // Replace with actual logic to get cleaningConfigId
    } catch (error) {
      console.error('文件加载失败:', error);
      ElMessage.error('文件加载失败: ' + error.message);
    }
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
};

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('上传失败');
};

// 导出结果
const handleExport = () => {
  ElMessage.success('导出成功');
};

// 开始清洗
const handleClean = async () => {
  if (!cleaningConfigId.value) {
    ElMessage.error('请先上传文件以获取清洗配置ID');
    return;
  }

  // 构建所有配置值
  const configPayload = {
    remove_name_enabled: basicConfig.value.removeName.value,
    remove_place_enabled: basicConfig.value.removeLocation.value,
    remove_id_enabled: basicConfig.value.removeIdCard.value,
    remove_phone_enabled: basicConfig.value.removePhone.value,
    uniform_number_enabled: advancedConfig.value.isRemoveNumber.value,
    normalize_address_enabled: advancedConfig.value.isRemoveOther.value,
    concat_lines_enabled: advancedConfig.value.isRemoveContent.value,
    sort_data_enabled: advancedConfig.value.isRemovePolicy.value,
    customRules: customRules.value
  };

  try {
    const response = await request({
      url: `/system/cleanConfig/${cleaningConfigId.value}/clean`,
      method: 'put',
      data: configPayload
    });

    if (response.code === 200) {
      ElMessage.success('开始清洗');
      // 可以在这里处理清洗结果
      console.log('清洗结果:', response.data);
    } else {
      ElMessage.error(response.msg || '清洗失败');
    }
  } catch (error) {
    console.error('清洗失败:', error);
    ElMessage.error('清洗失败，请稍后重试');
  }
};

// 保存配置 - 调用后端接口
const handleSaveConfig = async () => {
  if (!cleaningConfigId.value) {
    ElMessage.error('请先上传文件以获取清洗配置ID');
    return;
  }

  // Map frontend config to backend fields
  const configPayload = {
    remove_name_enabled: basicConfig.value.removeName.value ? 1 : 0,
    remove_place_enabled: basicConfig.value.removeLocation.value ? 1 : 0,
    remove_id_enabled: basicConfig.value.removeIdCard.value ? 1 : 0,
    remove_phone_enabled: basicConfig.value.removePhone.value ? 1 : 0,
    uniform_number_enabled: advancedConfig.value.isRemoveNumber.value ? 1 : 0,
    normalize_address_enabled: advancedConfig.value.isRemoveOther.value ? 1 : 0,
    concat_lines_enabled: advancedConfig.value.isRemoveContent.value ? 1 : 0,
    sort_data_enabled: advancedConfig.value.isRemovePolicy.value ? 1 : 0
  };

  try {
    const response = await request({
      url: `/system/cleanConfig/${cleaningConfigId.value}/toggle`,
      method: 'put',
      data: configPayload
    });

    if (response.code === 200) {
      ElMessage.success('保存配置成功');
      // Log the returned values for testing
      console.log('Updated configuration:', response.data);
    } else {
      ElMessage.error(response.msg || '保存配置失败');
    }
  } catch (error) {
    console.error('保存配置失败:', error);
    ElMessage.error('保存配置失败: ' + error.message);
  }
};

// 修改基础清洗配置
const basicConfig = ref({
  removeName: { label: '是否启用删除姓名', value: 0, id: 1 },
  removeLocation: { label: '是否启用删除地名', value: 0, id: 2 },
  removeIdCard: { label: '是否启用删除身份证号', value: 0, id: 3 },
  removePhone: { label: '是否启用删除手机号码', value: 0, id: 4 }
});

// 修改高级清洗配置
const advancedConfig = ref({
  isRemoveNumber: { label: '是否启用统一数字格式', value: 0, id: 5 },
  isRemoveOther: { label: '是否启用统一其他格式', value: 0, id: 6 },
  isRemoveContent: { label: '是否启用多行内容拼接', value: 0, id: 7 },
  isRemovePolicy: { label: '是否启用政策内容拼接', value: 0, id: 8 }
});

// 自定义规则
const customPattern = ref('');
const customRules = ref([]);

// 添加自定义规则
const handleAddRule = () => {
  if (!customPattern.value) {
    ElMessage.warning('请输入正则表达式');
    return;
  }
  customRules.value.push(customPattern.value);
  customPattern.value = '';
  ElMessage.success('添加规则成功');
};

// 删除自定义规则
const handleRemoveRule = (index) => {
  customRules.value.splice(index, 1);
  ElMessage.success('删除规则成功');
};

// 修改处理配置切换函数
const handleConfigToggle = (config, key, val) => {
  if (key in basicConfig.value) {
    basicConfig.value[key].value = val;
  } else if (key in advancedConfig.value) {
    advancedConfig.value[key].value = val;
  }
  console.log(`Toggle ${key}:`, val);
};

// 修改重置方法
const handleReset = () => {
  fileInfo.value = {
    name: '',
    path: '',
    size: 0,
    createTime: ''
  };
  fileUrl.value = '';
  fileContent.value = '';
  docContent.value = '';
  
  // 重置所有配置为0
  Object.values(basicConfig.value).forEach(item => {
    item.value = 0;
  });
  Object.values(advancedConfig.value).forEach(item => {
    item.value = 0;
  });
  customRules.value = [];
  customPattern.value = '';
  
  ElMessage.success('重置成功');
};
</script>